//Sensor.c
//Kevin Gillespie
//19 April 2012

//Include files
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdint.h>
#include "i2c-dev.h"


int main(int argc, char *argv[])
{
	//Takes input from command line when the file is executed
	//    ./sensor <speed>
	int speed;
	if(argc != 2)
	{
		printf("Usage: %s speed\n",argv[0]);
	   return 1;
	}

	speed = atoi(argv[1]);
	printf("Using speed = %d\n", speed);

	//////////////Open device files///////////////////
	int device_file;
	char filename[20];
	int adapter_nr = 1; //ic2-# Snowball board has 4 different adapter numbers. GPIO pins on SDK are i2c-1

	snprintf(filename,19,"/dev/i2c-%d", adapter_nr); //open the file with read and write permissions
	device_file = open(filename, O_RDWR);

	if(device_file <0)//Error handling for file open
	{
		perror("ERROR in opening file 1");
	}
	else
	{
		printf("OPENED THE DEVICE FILE 1\n");
	}


	////////////////Open output file/////////////////
	FILE *data_file;
	data_file=fopen("data_file.txt", "a");




	////////Specify the address to read/////////////

	int temp_addr;
	temp_addr = 0x48;	//ADD0 connected to GND

	if(ioctl(device_file,I2C_SLAVE,temp_addr) < 0) //Specify the first slave address
	{
		perror("Error addressing the device_1");
	}
	else
	{
		printf("ADDRESS 1 SPECIFIED\n");
	}

	
	/////////////Read Temperature Sensor////////////

	
	printf("Entering while loop at speed: %d \n",speed);

	struct timeval start, end;
  	gettimeofday(&start,0);

	int i =0;
	int error_count = 0;
	char result[2];

	while(i<100000)//takes 30 samples then exits
	{
		//usleep(speed);
		
		if(read(device_file,result,2) <0) //reads 2 byte into result
		{
			perror("ERROR in i2c reading");
			error_count++;
		}
		//printf("Temp 1 = %d C \n",result[0]);
		i=i+1;
	}

	gettimeofday(&end,0);
	double time = (1000000.0*(end.tv_sec-start.tv_sec) + end.tv_usec-start.tv_usec)/1000000.0;

	fprintf(data_file,"Time to take reading = %f \n",time);
	fprintf(data_file,"Speed = %d \n",speed);
	fprintf(data_file,"Number of readings = %d \n",i);
	fprintf(data_file,"Number of errors = %d \n\n\n", error_count);

	fclose(data_file);

	/////////////Close the device file////////////////////
	if(close(device_file) < 0 )
	{
		perror("Error closing device_file");
	}
	else
	{
		printf("Closed device file sucessfully\n");
	}
}


	

